package controllers

import (
	//	"encoding/json"
	//	"errors"
	"gitee.com/lzqysoft/ilive/libs"
	"gitee.com/lzqysoft/ilive/models"
	//	"os"
	"time"
	//	"path"
	"reflect"
	"strconv"
	"strings"

	"github.com/astaxie/beego"
)

// oprations for Video
type VideoController struct {
	CommonController
}

func (c *VideoController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Update", c.Update)
	c.Mapping("Delete", c.Delete)
	c.Mapping("GetVideoList", c.GetVideoList)
	//	c.Mapping("Dianbo_watch", c.Dianbo_watch)
	c.Mapping("VideoWatch", c.VideoWatch)
	c.Mapping("DeleteVideos", c.DeleteVideos)
	//	c.Mapping("VideoUpload", c.VideoUpload)
	//	c.Mapping("VideoStatisticPage", c.VideoStatisticPage)
	//	c.Mapping("VideoStatistic", c.VideoStatistic)
	c.Mapping("VideoList", c.VideoList)
	c.Mapping("VideoCancel", c.VideoCancel)
	//	c.Mapping("GetDiskInfoPage", c.GetDiskInfoPage)
	c.Mapping("GetUsedPercent", c.GetUsedPercent)
	c.Mapping("GetVideoUserByVideo", c.GetVideoUserByVideo)

}

// @Title Post
// @Description create Video
// @Param	body		body 	models.Video	true		"body for Video content"
// @Success 201 {int} models.Video
// @Failure 403 body is empty
// @router / [post]
func (c *VideoController) Post() {
	user := c.user
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	//	org, err := models.GetOrganizationById(user.Organization.Id)
	if err != nil {
		c.RetError(ErrNoUser)
	}
	var v models.Video
	v.Dept = user.Dept[0]
	v.Organization = user.Organization
	v.OrgName = user.Organization.Name
	v.Type = 1
	v.Title = sdata["Title"].(string)
	v.Url = sdata["Url"].(string)
	v.Img = sdata["Img"].(string)
	beego.Debug("v.Imgv.Img:", v.Img)
	scope := sdata["Scope"].(string)
	v.Scope, _ = strconv.ParseInt(scope, 10, 64)
	vstatus := sdata["Status"].(string)
	v.Status, _ = strconv.ParseInt(vstatus, 10, 64)
	size := sdata["Size"].(string)
	v.Size, _ = strconv.ParseInt(size, 10, 64)
	length := sdata["Length"].(string)
	v.Length, _ = strconv.Atoi(length)
	v.Longtime = sdata["Longtime"].(string)
	v.Remark, _ = sdata["Remark"].(string)
	v.Creater = user.Name
	v.Ctime = time.Now()
	v.Updater = v.Creater
	v.Utime = v.Ctime
	id, err := models.AddVideo(&v)
	if err != nil {
		beego.Debug(err, v)
		c.RetError(ErrDatabase)
	}
	if v.Scope == 3 {
		users := strings.Split(sdata["users"].(string), ",")
		for _, e := range users {
			uid, _ := strconv.ParseInt(e, 10, 64)
			_, err = models.AddUserVideo(uid, id)
			c.Dlog("添加了点播资源用户授权，id：", id)
		}
	}
	c.Dlog("添加了视频资源", id)
	c.RetSuccess(id)
}

// @Title Get
// @Description get Video by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Video
// @Failure 403 :id is empty
// @router /:id [get]
func (c *VideoController) GetOne() {
	id, _ := c.GetInt64(":id")
	v, err := models.GetVideoById(id)
	if err != nil {
		c.RetError(ErrNoData)
	}
	c.RetSuccess(v)
}

// @Title Get All
// @Description get Video
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Video
// @Failure 403
// @router /GetAll [post]
func (c *VideoController) GetAll() {
	user := c.user
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var fields []string
	var sortby []string
	var order []string
	query := make(map[string]interface{})
	var limit int64 = -1
	var offset int64 = 0
	sdata, _ := rdata.(map[string]interface{})
	//	beego.Debug("statastatatat:", sdata)
	//	role, err := models.GetRoleByUserId(user.Id)
	if err != nil {
		c.RetError(ErrPermission)
	}
	query["Isdelete"] = "0"
	//用户角色不是系统管理员的筛选单位
	switch user.Role[0].Type {
	case 1:
		query["Organization__Id"] = strconv.FormatInt(user.Organization.Id, 10)
	case 2:
		ids := models.GetDeptChildrenStr(user.Dept[0].Id)
		query["Dept__Id__in"] = *ids
	}
	ipage, _ := sdata["page"].(string)
	page, _ := strconv.ParseInt(ipage, 10, 64)
	ipagesize, _ := sdata["pagesize"].(string)
	pagesize, _ := strconv.ParseInt(ipagesize, 10, 64)
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * pagesize
	}
	limit = pagesize
	l, count, err := models.GetAllVideo(query, fields, sortby, order, offset, limit)
	if err != nil {
		c.RetError(ErrNoData)
	}
	tabledata := make(map[string]interface{})
	tabledata["total"] = count
	tabledata["tabledata"] = l
	c.RetSuccess(tabledata)
}

// @Title Update
// @Description update the Video
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Video	true		"body for Video content"
// @Success 200 {object} models.Video
// @Failure 403 :id is not int
// @router /Update [post]
func (c *VideoController) Update() {
	user := c.user
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	sid := sdata["Id"].(string)
	id, _ := strconv.ParseInt(sid, 10, 64)
	v, err := models.GetVideoById(id)
	if err != nil {
		c.RetError(ErrNoData)
	}
	v.Title = sdata["Title"].(string)
	scope, _ := sdata["Scope"].(string)
	v.Scope, _ = strconv.ParseInt(scope, 10, 64)
	vstatus, _ := sdata["Status"].(string)
	v.Status, _ = strconv.ParseInt(vstatus, 10, 64)
	v.Remark, _ = sdata["Remark"].(string)
	v.Updater = user.Name
	v.Utime = time.Now()

	err = models.UpdateVideoById(v)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	if v.Scope == 3 {
		models.DeleteUserVideoByVideoId(id)
		users := strings.Split(sdata["users"].(string), ",")
		for _, e := range users {
			uid, _ := strconv.ParseInt(e, 10, 64)
			models.AddUserVideo(uid, v.Id)
			c.Dlog("添加了视频资源用户授权，id：", v.Id)
		}
	}

	c.Dlog("修改视频信息", id)
	c.RetSuccess(id)
}

// @Title Delete
// @Description delete the Video
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /Delete [post]
func (c *VideoController) Delete() {
	//	user, _ := c.GetUserinfo()
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	sid := sdata["Id"].(string)
	id, err := strconv.ParseInt(sid, 10, 64)
	if err != nil {
		c.RetError(ErrInputData)
	}
	if err := models.DeleteVideo(id); err == nil {
		c.Dlog("删除了点播资源信息", id)
		c.RetSuccess(id)
	}
	c.RetError(ErrDatabase)
}

// @Title GetVideoList
// @Description 获取点播列表
// @Success GetVideoList success!
// @Failure
// @router /GetVideoList [get]
func (c *VideoController) GetVideoList() {
	//	var query map[string]string = make(map[string]string)
	user := c.user
	//	role, err := models.GetRoleByUserId(user.Id)
	//用户角色不是系统管理员的筛选单位
	var l []interface{}
	var err error
	if user.Role[0].Type > 0 {
		l, _, err = models.GetVideoByOrgid(user)

	} else {
		l, _, err = models.GetVideolist()

	}
	if err != nil {
		c.RetError(ErrNoData)
	}
	c.RetSuccess(l)
}

// @Title VideoWatch
// @Description 点击视频次数更新
// @Success VideoWatch success!
// @Failure
// @router /VideoWatch [post]
func (c *VideoController) VideoWatch() {
	//	user, _ := c.GetUserinfo()
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	beego.Debug("VideoWatchsdatasdatasdata:", sdata)
	sid := sdata["id"].(string)
	vid, _ := strconv.ParseInt(sid, 10, 64)
	path := sdata["url"].(string)
	videotype := sdata["type"].(string)

	if videotype == "rtmp/flv" {
		err = models.AddLiveChannelClicks(path)
		if err != nil {
			c.RetError(ErrDatabase)
		}
	} else {
		err = models.AddVideoClicks(path)
		if err != nil {
			c.RetError(ErrDatabase)
		}
	}
	c.RetSuccess(vid)
}

// @Title DeleteVideos
// @Description DeleteVideos
// @Success DeleteVideos success!
// @Failure
// @router /DeleteVideos [post]
func (c *VideoController) DeleteVideos() {
	//	user, _ := c.GetUserinfo()
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.([]interface{})
	for _, value := range sdata {
		eid := value.(string)
		id, _ := strconv.ParseInt(eid, 10, 64)
		if err := models.DeleteVideo(id); err == nil {
			if err != nil {
				c.RetError(ErrDatabase)
			}
			c.Dlog("删除了点播资源", id)

		}

	}
	c.RetSuccess(sdata)
}

// @Title VideoCancel
// @Description VideoUpload取消上传文件
// @Success VideoUpload success!
// @Failure
// @router /VideoCancel [post]
func (c *VideoController) VideoCancel() {
	user := c.user
	beego.Debug(user)
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	//	Url := "/data/root/" + sdata["Url"].(string)
	//	os.Remove(Url)
	file := sdata["Url"].(string)
	libs.DeleteFile(file)
	c.RetSuccess(file)

	//	c.RetSuccess(v)

}

// @Title GetDiskInfo
// @Description 获取硬盘信息
// @Success GetDiskInfo success!
// @Failure
// @router /GetDiskInfo [get]
func (c *VideoController) GetDiskInfo() {
	data := make(map[string]interface{})
	disk := libs.DiskUsage("/data/root")
	data["all"] = disk.All
	data["used"] = disk.Used
	data["free"] = disk.Free
	beego.Debug("sys info is:", data)
	c.Data["json"] = data
	c.ServeJSON()
}

// @Title GetUsedPercent
// @Description 获取已用空间百分比
// @Success GetUsedPercent success!
// @Failure
// @router /GetUsedPercent [get]
func (c *VideoController) GetUsedPercent() {
	percent := models.GetUsedDiskPercent(c.GetSession("org").(models.Organization))
	beego.Debug("uesd percent :", percent, "%")
	c.Data["json"] = percent
	c.ServeJSON()
}

// @Title 获取点播视频的人员授权
// @Description 获取点播视频的人员授权
// @Success GetVideoUserByVideo success!
// @Failure
// @router /GetVideoUserByVideo/:id [get]
func (c *VideoController) GetVideoUserByVideo() {
	id, _ := c.GetInt64(":id")
	video, err := models.GetVideoById(id)
	if err != nil {
		c.RetError(ErrPermission)
	}
	var users []int64
	for _, v := range video.User {
		users = append(users, v.Id)
	}
	c.RetSuccess(users)
}

// @Title VideoList
// @Description 获取视频列表分页
// @Success VideoList success!
// @Failure
// @router /VideoList [post]
func (c *VideoController) VideoList() {
	user := c.user
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	beego.Debug("CurrentPageIndex:", sdata["CurrentPageIndex"], reflect.TypeOf(sdata["CurrentPageIndex"]))
	beego.Debug("PageSize:", sdata["PageSize"], reflect.TypeOf(sdata["PageSize"]))
	CurrentPageIndex := sdata["CurrentPageIndex"].(string)
	PageSize := sdata["PageSize"].(string)
	pageindex, _ := strconv.Atoi(CurrentPageIndex)
	pagesize, _ := strconv.Atoi(PageSize)
	//	log.Debug("1111111111:", CurrentPageIndex, PageSize)
	var l []interface{}
	//	var cl int64
	if user.Role[0].Type > 0 {
		l, _, err = models.GetVideoByOrgid(user)

	} else {
		l, _, err = models.GetVideolist()

	}
	if err != nil {
		c.RetError(ErrNoData)
	}
	beego.Debug((pageindex-1)*pagesize, pagesize)
	beego.Debug(user.Role[0].Type)
	beego.Debug("ddaaata:", l)
	if len(l) < (pageindex-1)*pagesize {
		c.RetError(ErrNoData)
	} else {
		if len(l) > (pageindex)*pagesize {
			c.RetSuccess(l[(pageindex-1)*pagesize : pagesize])
		} else {
			c.RetSuccess(l[(pageindex-1)*pagesize:])
		}

	}

}
